<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class enter2winController extends appRain_Base_Core
{
    public $name = 'Enter2win';

    /**
     * Execute before the action
     */
    public function __preDispatch()
    {
    }

    /**
     * This is blog starting page
     * We have configure this page from
     * URI_Manager >> Boot_Router
     */
    public function indexAction($action=null, $id=null,$page = 1)
    {
    }
	
	public function retailerlinksAction(){
		$this->setAdminTab('enter2win');
		
		$dataList = App::InformationSet('e2wcontest')->findAll();
		$this->set('dataList',$dataList);
		
	}
	
	public function displaymessageAction($message=null){
		$this->setMessage($message);
	}

    /**
     * This page is called by an AJAX
     * request. We have have set the layout "empty"
     *
     * Empty layout never attach any template from "View"
     */
    public function contestAction($id=null)
    {
		$contest = App::InformationSet()->findById($id);
		
		if($contest['conteststatus'] == 'Inctive' OR $contest['contatusround']  == 'Inctive'){
			$this->redirect('/enter2win/displaymessage/Sorry,+Contest+is+not+started');
		}
		$this->set('contest',$contest);
		
		$User = App::MemberManager()->checkAppUserLogin();		
		$this->set('id',$id);
	
        if(!empty($this->data)){
			try{
				$promocode = $this->data['Contest']['promocode'];
				$codeData = App::InformationSet('e2wpromocode')->findByPromocode($promocode);

				if(empty($codeData)){
					throw new AppException($this->__("Invalid Coupon code."));
				}
				else if ($codeData['contest'] != $id){					
					throw new AppException($this->__("Code is not belongs to this contest."));
				}
				else if($codeData['status'] == 'Inctive'){
					throw new AppException($this->__("Coupon code is not Active."));
				}
				/*else if(
					($contest['contatusround'] == '1' and $codeData['status'] == 'SecondChance') Or
					($contest['contatusround'] == '2' and $codeData['status'] == 'Used')
				)*/
				else if(
					($codeData['status'] == 'Used')
				){
					throw new AppException($this->__("Coupon code is already used."));
				}
				else {
					$counter = $contest['entrycounter'] + 1;			
					$winnerchance = $contest['winnerchance'];
					
					$status = ($codeData['status'] != 'SecondChance') ?  'SecondChance' : 'Used';
					//$status = ($contest['contatusround'] == '1') ?  'SecondChance' : 'Used';
					
					// Update Winner	
					if($counter % $winnerchance == 0){
						App::InformationSet('e2wpromocode')
						->setId($codeData['id'])
						->setWinonround($contest['contatusround'])
						->setWindate(date('Y-m-d'))						
						->Save();
					}
					
					App::InformationSet('e2wcontest')
						->setId($id)
						->setEntrycounter($counter)
						->Save();

					$obj = App::InformationSet('e2wpromocode')
						->setId($codeData['id'])
						->setUser($User['id'])						
						->setStatus($status)
						->Save();
					$status = 'Success';	
					if($codeData['status'] == 'SecondChance'){
						throw new AppException($this->__("Coupon code accepted successfully in second chance."));
					}
					else {
						throw new AppException($this->__("Coupon code accepted successfully."));
					}
				}
				
			}
			catch (AppException $e){
				echo App::Load("Module/Cryptography")
					->jsonEncode(array(
						"_status" =>(isset($status) ? $status : 'Error'),
						"_message"=>$e->getMessage()
					));
				exit;	
			}
		}
    }

	public function contest_winnersAction($contestId=null)
	{
		$this->setAdminTab('enter2win');
		$Winers = App::InformationSet('e2wpromocode')->findAll(null,
			array(
				array("contest"=>"{$contestId}"),
				'AND',
				array("windate"=>"","cnd"=>"<>")
			)
		);
		$this->set('dataList',$Winers);
	}
	
	
	public function promocodebatchAction($contestid=null)
	{
		$this->setAdminTab('enter2win');
		
		if(!empty($this->data)){
		
			if( $this->data['Batch']['contest'] == ''){
				App::Module('Notification')->Push("Select a content.",'error');
				 $this->redirect("/enter2win/promocodebatch");
				 exit;
			}
			else {
				$nof = $this->data['Batch']['nof'];
				for($ii=1; $ii <= $nof; $ii++){				
					$obj = App::InformationSet('e2wpromocode')
						->setId(null)
						->setStatus('Active')
						->setContest($this->data['Batch']['contest'])						
						->setPromocode(rand(1000000000,9999999999))
						->setRedeemed('No')
						->setWinonround('')
						->setWindate('')
						->setUser('')
						->setRedeemeddate('')
						->Save();
				}
				App::Module('Notification')->Push("Updated successfuly.");
				$this->redirect("/enter2win/promocodebatch/{$this->data['Batch']['contest']}");
				exit;
			}
		}
		$promoList = array();
		if(isset($contestid)){
			$promoList = App::InformationSet('e2wpromocode')->findAllByContest($contestid);
		}
		
		$this->set('contestid',$contestid);
		$this->set('promoList',$promoList);
	}
		 
		 
    /**
     * Manage Blog Comments
     * We have render this page under Blog tab
     * in admin panel.
     */
    /*public function managecommentAction($action=null, $id = null)
    {
        // Set Admin Tab
        $this->setAdminTab('blog');

        // Update the post if
        // the action is set to 'update'
        if($action == 'update')
        {
            $this->addons = Array('rich_text_editor','date_picker');

            if(!empty($this->data))
            {
                $this->data['Comment']['id'] = $id;
                $this->data['Comment']['dated'] = date('Y-m-d H:i:s',strtotime("{$this->data['Comment']['dated']['year']}-{$this->data['Comment']['dated']['month']}-{$this->data['Comment']['dated']['day']} {$this->data['Comment']['dated']['hour']}:{$this->data['Comment']['dated']['munite']}:{$this->data['Comment']['dated']['second']}"));

                App::Model('Comment')->Save($this->data);

                $this->redirect("/appblog/managecomment/");
                exit;
            }

            $comment = App::Model('Comment')->findById($id);
            $this->set("comment",$comment);
            $this->set('id',$id);
        }
        else
        {
            $this->addons = Array('row_manager');

            // Fetch all comments form 'Comment' model
            // and assign to template
            $comments = App::Model('Comment')->paging("type='Blog' ORDER BY id DESC",$this->get_config('default_pagination'));
            $this->set("comments",$comments);
        }

        $this->set("action",$action);
    }*/
}
